<script setup lang="ts">
import { ref, onMounted, onUpdated, render } from 'vue'
import DataTable from 'datatables.net-vue3'
import DataTablesCore from 'datatables.net-bs4'
import 'datatables.net-select'
import '../../plugin/datatables.net-responsive'
import { db } from '../../db/db'
import { getUsers, getOrganize } from '../../util/SessionUtil'
import $ from 'jquery'
import DatatableRender from '../../components/DatatableRender.vue'

DataTable.use(DataTablesCore)

const options: any = {
    responsive: true,
    select: true,
    aaSorting: [[1, 'desc']],// 排序
    language: {
        "sProcessing": "处理中...",
        "sLengthMenu": "显示 _MENU_ 项结果",
        "sZeroRecords": "没有匹配结果",
        "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
        "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
        "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
        "sInfoPostFix": "",
        "sSearch": "搜索:",
        "sUrl": "",
        "sEmptyTable": "表中数据为空",
        "sLoadingRecords": "载入中...",
        "sInfoThousands": ",",
        "oPaginate": {
            "sFirst": "首页",
            "sPrevious": "<",
            "sNext": ">",
            "sLast": "末页"
        },
        "oAria": {
            "sSortAscending": ": 以升序排列此列",
            "sSortDescending": ": 以降序排列此列"
        },
        "select": {
            "rows": {
                _: '选择了 %d 行',
                1: '选择了 1 行'
            }
        }
    },
    autoWidth: true
}

const tableData: any = ref([])

const columns = [
    { data: 'organizeId', title: '组织ID', responsivePriority: 4, className: 'none' },
    { data: 'salvationTypeName', title: '救助类型', responsivePriority: 1 },
    { data: null, title: '操作', responsivePriority: 2, render: '#operate' },
]

let dt
const table = ref()

const users = getUsers()

const loadTableData = async () => {
    let tempData = []
    const organize: any = await getOrganize(users.username)
    if (organize) {
        const organizeSalvationType = await db.organizeSalvationType.where('organizeId').equals(organize[0].organizeId).toArray()
        for (let i in organizeSalvationType) {
            const salvationType = await db.salvationType.where('salvationTypeId').equals(organizeSalvationType[i].salvationTypeId).toArray()
            tempData.push({
                organizeId: organizeSalvationType[i].organizeId,
                salvationTypeId: organizeSalvationType[i].salvationTypeId,
                salvationTypeName: salvationType[0].salvationTypeName
            })
        }

        tableData.value = tempData
    }

}

const salvationTypeData: any = ref([])

onMounted(async () => {
    loadTableData()
    const salvationType = await db.salvationType.toArray()
    salvationTypeData.value = salvationType
})

onUpdated(() => {
    // 因异步加载数据，导致宽度变化，需要重画
    dt = table.value.dt
    dt.columns.adjust().draw()
    $('.carousel').carousel()

    $('.datatable').off('click', '.del').on("click", '.del', function (e: any) {
        del(e.currentTarget.dataset.organizeId, e.currentTarget.dataset.salvationTypeId)
    })

})

const tipModal = ref({
    class: '',
    title: '',
    content: ''
})

const confirmModal = ref({
    class: '',
    title: '',
    content: '',
    callBack: '',
    data: {}
})


const del = (organizeId: string, salvationTypeId: string) => {

    confirmModal.value.class = 'text-danger'
    confirmModal.value.title = '删除确认'
    confirmModal.value.content = '您好，确认进行删除吗？'
    confirmModal.value.callBack = 'del'


    confirmModal.value.data = {
        organizeId: organizeId,
        salvationTypeId: salvationTypeId
    }
    $('#confirmModal').modal('show')
}

const addType = async () => {
    const organize: any = await getOrganize(users.username)
    if (organize) {
        const organizeSalvationType = await db.organizeSalvationType.where('organizeId').equals(organize[0].organizeId).toArray()
        let tempOs = []
        for (let i in salvationTypeData.value) {
            let hasV = false
            for (let j in organizeSalvationType) {
                if (salvationTypeData.value[i].salvationTypeId == organizeSalvationType[j].salvationTypeId) {
                    hasV = true
                    break
                }
            }
            if (!hasV) {
                tempOs.push(salvationTypeData.value[i])
            }
        }

        salvationTypeData.value = tempOs
    }

    $('#addModal').modal('show')
}

const confirmEx = (callBack: string, data: any) => {
    $('#confirmModal').modal('hide')

    if (callBack === 'del') {

        db.organizeSalvationType.where('organizeId').equals(Number(data.organizeId))
            .and(os => os.salvationTypeId == Number(data.salvationTypeId)).delete()

        tipModal.value.class = 'text-success'
        tipModal.value.title = '删除成功'
        tipModal.value.content = '您好，类型已删除！'
        $('#tipModal').modal('show')
    }
    loadTableData()
}

const form = ref({
    salvationTypeId: ''
})
const formErr = ref({
    salvationTypeId: false
})
const formMsg = ref({
    salvationTypeId: ''
})

function checkSalvationTypeId() {
    formErr.value.salvationTypeId = false
    formMsg.value.salvationTypeId = ''
    if (form.value.salvationTypeId === '') {
        formErr.value.salvationTypeId = true
        formMsg.value.salvationTypeId = '请选择类型'
        return false
    }
    return true
}

const okAddType = async () => {
    if (!checkSalvationTypeId()) {
        return false
    }
    const organize: any = await getOrganize(users.username)
    if (organize) {
        db.organizeSalvationType.add({
            organizeId: organize[0].organizeId,
            salvationTypeId: Number(form.value.salvationTypeId)
        })
    }

    $('#addModal').modal('hide')
    tipModal.value.class = 'text-success'
    tipModal.value.title = '添加成功'
    tipModal.value.content = '您好，类型已添加成功！'
    $('#tipModal').modal('show')
    loadTableData()

    return true
}

</script>
<template>
    <div class="col-md-9 col-lg-10">
        <div class="br-pagebody mg-t-5 pd-x-30">
            <div class="br-section-wrapper">
                <div class="row">
                    <div class="col-md-12">
                        <button type="button" class="btn btn-primary float-right m-4" @click="addType">添加</button>
                    </div>
                    <div class="col-md-12">
                        <DataTable :options="options" :data="tableData" :columns="columns"
                            class="table responsive nowrap" ref="table">
                            <template #operate="props">
                                <div class="btn-group operate" role="group" aria-label="Basic example">
                                    <button type="button" class="btn btn-danger btn-sm del"
                                        :data-organize-id="props.rowData.organizeId"
                                        :data-salvation-type-id="props.rowData.salvationTypeId">删除</button>
                                </div>
                            </template>
                        </DataTable>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="tipModal" tabindex="-1" aria-labelledby="tipModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" :class="tipModal.class" id="tipModalLabel">{{ tipModal.title }}</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    {{ tipModal.content }}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!--确认Modal-->
    <div class="modal fade" id="confirmModal" tabindex="-1" aria-labelledby="confirmModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" :class="confirmModal.class" id="confirmModalLabel">{{ confirmModal.title }}
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    {{ confirmModal.content }}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary"
                        @click="confirmEx(confirmModal.callBack, confirmModal.data)">确定</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addModalLabel">添加救助类型</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form>
                        <div class="form-group">
                            <select class="form-control" :class="formErr.salvationTypeId ? 'is-invalid' : ''"
                                v-model="form.salvationTypeId">
                                <option value="">请选择类型</option>
                                <option v-for="salvationType in salvationTypeData"
                                    :value="salvationType.salvationTypeId">
                                    {{ salvationType.salvationTypeName }}
                                </option>
                            </select>
                            <div class="invalid-feedback">
                                {{ formMsg.salvationTypeId }}
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" @click="okAddType">确定</button>
                </div>
            </div>
        </div>
    </div>
</template>
<style>
@import 'datatables.net-bs4';
</style>